package main

import (
	"fmt"
	"html/template"
	"io/ioutil"
	"net"
	"net/http"
	"strings"
	"time"
	"os/exec"
)

/**
 * 定义路由集和
 */
var routes map[string]string = map[string]string{
	"/":      "index",
	"/whois": "whois",
}

func routeAction(w http.ResponseWriter, r *http.Request) {

	/*
		r.ParseForm()
		fmt.Print(r.Form)
		fmt.Print(r.URL.Path)
		fmt.Print(r.URL.Scheme)
	*/

	fmt.Fprint(w, "Hello, Go Web!!")
}

func route(w http.ResponseWriter, r *http.Request) {

}

func whois(w http.ResponseWriter, r *http.Request) {

	r.ParseForm()

	fmt.Print("Hello,Whois!!\r\n")

	for k, v := range r.Form {

		fmt.Print("key:", k, " value :", strings.Join(v, ""), "\r\n")

	}

	//var _whois_server = "whois.markmonitor.com:43"
	var _whois_server = "whois.iana.org:43";

	conn, err := net.DialTimeout("tcp", _whois_server, time.Second*10)

	if err != nil {

		//log.Fatal(err)
		fmt.Print("Error", err)
		return
	}

	domain := strings.Join(r.Form["domain"], "")

	conn.Write([]byte(domain + "\r\n"))

	result, err := ioutil.ReadAll(conn)

	fmt.Fprint(w, string(result))
}

func tpl(w http.ResponseWriter, r *http.Request) {
	html := `
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Go,Web!!</title>
</head>
<body>
{{.Word}}
</body>
</html>
`
	tmpl, err := template.New("hello").Parse(html)

	if err != nil {
		fmt.Print("Error: ", err, "\r\n")
	}

	data := struct {
		Word string
	}{
		Word: "HaHa, I am Go!!",
	}

	err = tmpl.Execute(w, data)

	if err != nil {
		fmt.Print("Render Error: ", err, "\r\n")
	}
}

func w(w http.ResponseWriter, r *http.Request) {

	r.ParseForm()

	domain := strings.Join(r.Form["domain"], "")

	if "" != domain {

		cmd := exec.Command("whois", domain)
		out, _ := cmd.Output()
//fmt.Print("Error: ", err, out)
		//if err != nil {
		//	fmt.Fprint(w, "Query domain error:" + domain + "!\r\n")
		//}else{
		//	fmt.Fprint(w, string(out))
		//}

		fmt.Fprint(w, string(out))
	}
}

var _ = 100

func main() {

	//for k, v := range routes {

	//reflect.ValueOf()
	//http.HandleFunc(k, fun())
	//}

	http.HandleFunc("/", routeAction)
	http.HandleFunc("/whois", whois)
	http.HandleFunc("/tpl", tpl)
	http.HandleFunc("/w", w)

	host := "127.0.0.1:8000"

	err := http.ListenAndServe(host, nil)

	fmt.Print("ListenAndServe:", err)

}

